#include "mediafactory.h"

MediaFactory::MediaFactory(QObject *parent) :
    QObject(parent)
{
}

///
/// Preparing to build all nessesary objects
void MediaFactory::fetchObjects()
{
    QSqlQuery query("SELECT ID, title, year, file_path, checksum FROM movies");
    QString title;
    QString filePath;
    int year;
    int id;
    while (query.next()) {
        id = query.value(0).toInt();
        title = query.value(1).toString();
        year = query.value(2).toInt();
        filePath = query.value(3).toString();

        Movie *movie = new Movie(id);
        movie->setTitle(title);
        movie->setYear(year);
        movie->setFilePath(filePath);

        QSharedPointer<Movie> pMovie(movie);
        movieList_.push_back(pMovie);
    }
}

///
/// @param  id      The internal database id of the movie
///
/// Creates the movie object for an id and returns the pointer to it
Movie *MediaFactory::movie(int id)
{
    QSqlQuery query;
    Movie *movie;
    bool state;

    query.prepare("SELECT ID, IMAGE_ID, title, year, file_path, checksum, tmdb_id FROM movies WHERE ID = :id");
    query.bindValue(":id", id);
    state = query.exec();
    //qDebug() << query.lastQuery();
    if (!state)
        qDebug() << query.lastError().text();

    while (query.next()) {
        movie = new Movie(id);
        movie->setImageId(query.value(1).toInt());
        movie->setTitle(query.value(2).toString());
        movie->setYear(query.value(3).toInt());
        movie->setFilePath(query.value(4).toString());
        movie->setTmdbId(query.value(6).toInt());
    }

    return movie;
}

///
/// @return     The media list
///
/// Returns the media list
MovieList &MediaFactory::getData()
{
    fetchObjects();

    return movieList_;
}
